var PROVINCIALDEFAULTOPTION="<option value='0'>--请选择省级公司--</option>";
var PROVINCIALSPECIALTOPTION="<option value='-1'>全部省级公司</option>";
var MUNICIPALDEFAULTOPTION="<option value='0'>--请选择市级公司--</option>";
var MUNICIPALSPECIALTOPTION="<option value='-1'>全部市级公司</option>";
var CENTERDEAFAULTOPIONT="<option value='0'>--请选择理赔中心--</option>";
var CENTERSPECIALTOPTION="<option value='-1'>全部理赔中心</option>";
var HOME_OFFICE_LEVEL=1;
var PROVINCIAL_LEVEL=2;
var MUNIPITAL_LEVEL=3;
var CLAIM_CENTER_LEVEL=4;
var ALERT_MESSAGE_DONT_SELECT_COMPANY="请选择公司再做查询！";

$(document).ready(function() {	

 initDropDownSelectMenu();
 //initHomeOfficeDiv();	
 initAddButtonDiv();
 initButton();

});

function getSubordinate(parentCompanyId,level){
	var menuLayOut=$("#menuLayOut").val();
	var menuObj=evalJSON(menuLayOut);
	menuObj.currentSelectedCompanyId=-1;
	menuObj.parentCompanyId=parentCompanyId;
	menuObj.currentSelectedCompanyLevel=parseInt(level)+1;
	//set json string to hidden string
	var jsonStr=evalJSONString(menuObj);
	//clear page number
	$("#_p_currentPage_id").val("");
	$("#_p_totalPage_id").val("");	
	$("#menuLayOut").val(jsonStr);
	//submit
	submitActionByMethod('#form1','queryCompany');
}

function initButton(){
	var menuLayOut=$("#menuLayOut").val();
	var menuObj=evalJSON(menuLayOut);	
	var userCompanyLevel=menuObj.userCompanyLevel;
	var currentCompanyLevel=menuObj.currentSelectedCompanyLevel;
	if(currentCompanyLevel==userCompanyLevel){
		$("#deleteButton2").css("display","none");
	}
	if(currentCompanyLevel==1){
		$("#updateButton2").css("display","none");
	}
	
}

function initAddButtonDiv(){
	var menuLayOut=$("#menuLayOut").val();
	var menuObj=evalJSON(menuLayOut);	
	var userCompanyLevel=menuObj.userCompanyLevel;	
	if(userCompanyLevel==CLAIM_CENTER_LEVEL){
		$("#addCompanyButton").css("display","none");
	}
	
}

/*function initHomeOfficeDiv(){
	var menuLayOut=$("#menuLayOut").val();
	var menuObj=evalJSON(menuLayOut);	
	var userCompanyLevel=menuObj.userCompanyLevel;	
	if(userCompanyLevel!=HOME_OFFICE_LEVEL){
		hideClass(".homeofficeDetail");
	}
	
}*/

function initDropDownSelectMenu(){
	//add default option and special option to select drop down menu
	/*var maxProvincialIndex=$("#provincial option:last").attr("index");
	var maxMenterIndex=$("#municipal option:last").attr("index");
	var maxCenterIndex=$("#center option:last").attr("index");
	if(maxProvincialIndex>0){
		addSubOptionByPostion('#provincial',PROVINCIALSPECIALTOPTION);
	}
	if(maxMenterIndex>0){
		addSubOptionByPostion('#municipal',MUNICIPALSPECIALTOPTION);
	}
	if(maxCenterIndex>0){
		addSubOptionByPostion('#center',CENTERSPECIALTOPTION);
	}*/
	//control disable attribute of drop down menu
	var menuLayOut=$("#menuLayOut").val();
	//alert(menuLayOut);
	var menuObj=evalJSON(menuLayOut);	
	var userCompanyLevel=menuObj.userCompanyLevel;	
	//var objStr=$.toJSON(menuObj);
	if(userCompanyLevel==PROVINCIAL_LEVEL){
		disableSelectMenu("#provincial");
	}else if(userCompanyLevel==MUNIPITAL_LEVEL){
		disableSelectMenu("#provincial");
		disableSelectMenu("#municipal");
	}else if(userCompanyLevel==CLAIM_CENTER_LEVEL){
		disableSelectMenu("#provincial");
		disableSelectMenu("#municipal");
		disableSelectMenu("#center");
	}
	//when user selected option which named all selected
	var currentSelectedCompanyId=menuObj.currentSelectedCompanyId;
	var currentSelectedCompanyLevel=menuObj.currentSelectedCompanyLevel;
	if(currentSelectedCompanyId==-1){
		if(currentSelectedCompanyLevel==PROVINCIAL_LEVEL){
			$("#provincial").val(-1);
			
		}else if(currentSelectedCompanyLevel==MUNIPITAL_LEVEL){
			$("#municipal").val(-1);
		}else if(currentSelectedCompanyLevel==CLAIM_CENTER_LEVEL){
			$("#center").val(-1);
		}
	}
	
}

//convert json string to json object
function evalJSON(strJson){
	return jQuery.parseJSON(strJson);
}

//convert json object to json string
function evalJSONString(objJson){
	return $.toJSON(objJson);
}

//disable select menu by id
function disableSelectMenu(id){
	$(id).attr("disabled",true);
}

//clear drop down select menu
function clearDropDownSelectMenu(id,option){
	$(id+' option').remove();
	$(id).append(option);
}
//add option to select menu
function addSubOptionByPostion(id,option){	
	$(id).append(option);
	
	
}
function resetQuery(provincialId,municipalId,centerId){
	
	var menuLayOut=$("#menuLayOut").val();
	var menuObj=evalJSON(menuLayOut);	
	var userCompanyLevel=menuObj.userCompanyLevel;	
	resetLevel(userCompanyLevel,provincialId,municipalId,centerId);
}
function resetLevel(level,provincialId,municipalId,centerId){
	
	if(level==1){
		$(provincialId).val(0);
		$(municipalId).html(MUNICIPALDEFAULTOPTION);
		$(municipalId).val(0);
		$(centerId).html(CENTERDEAFAULTOPIONT);
		$(centerId).val(0);
	} else if (level==2){
		$(municipalId).val(0);
		$(centerId).html(CENTERDEAFAULTOPIONT);
		$(centerId).val(0);
	} else if (level==3){
		$(centerId).val(0);
	}
}

//reset municipal menu by ajax
function getMunicipal(){
	
	 var selectedProvincialCompany=$("#provincial").val();
	 
	 if(selectedProvincialCompany==0||selectedProvincialCompany==-1){
	   	clearDropDownSelectMenu('#center',CENTERDEAFAULTOPIONT);
		clearDropDownSelectMenu('#municipal',MUNICIPALDEFAULTOPTION);
		return;
	 }else{
      addOptionByAjax('admin/ajaxGetMunicipalList.action',selectedProvincialCompany,'#municipal',MUNICIPALDEFAULTOPTION,MUNICIPALSPECIALTOPTION);
  		clearDropDownSelectMenu('#center',CENTERDEAFAULTOPIONT);
	 }   
}

//reset center menu by ajax
function getCenter(){		
	 var selectedMunicipalCompany=$("#municipal").val();	 
	 if(selectedMunicipalCompany==0||selectedMunicipalCompany==-1){
   	   clearDropDownSelectMenu('#center',CENTERDEAFAULTOPIONT);
   	   return;
   }else{ 
	  addOptionByAjax('admin/ajaxGetClaimCenter.action',selectedMunicipalCompany,'#center',CENTERDEAFAULTOPIONT,CENTERSPECIALTOPTION);
 	} 
}




function addOptionByAjax(url,selectedCompanyId,dropDownMenuId,option,specialOption){
	 $.ajax({
         url: url,
         data: 'companyId='+selectedCompanyId,
         dataType: "json",
         cache: false,
         success: function(json){ 
          var companys = eval(json);
	   	     clearDropDownSelectMenu(dropDownMenuId,option);	
	   	  if(companys.length>0){
 	   	     addSubOptionByPostion(dropDownMenuId,specialOption);
 	   	    }
             $.each(companys,function(i, company){	
          	    $(dropDownMenuId).append("<option value='"+company.companyId+"'>"+company.companyName+"</option>");
            });  
            
        },
 	       error: function(XMLHttpRequest, textStatus, errorThrown) {
     	   alert(textStatus);
        }
     }); 
}

function queryCompanyByDropDownMenu(){
	var menuLayOut=$("#menuLayOut").val();
	var menuObj=evalJSON(menuLayOut);
	//able all
	ableAllSelectMenu();
	//get company value
	var provincialCompanyValue=$("#provincial").val();
	var municipalCompanyValue=$("#municipal").val();
	var centerCompanyValue=$("#center").val();
	var level;
	var selectedCompanyId;
	var parentCompanyId=-1;
	//provincial
	if(provincialCompanyValue==0){
		/*alert(ALERT_MESSAGE_DONT_SELECT_COMPANY);
		return false;*/
		level=parseInt(HOME_OFFICE_LEVEL);
		selectedCompanyId=menuObj.userCompanyId;
	}else if(provincialCompanyValue==-1){
		level=parseInt(PROVINCIAL_LEVEL);
		selectedCompanyId=-1;
		parentCompanyId=menuObj.userCompanyId;
	}
	//municipal
	else if(municipalCompanyValue==0){
		level=parseInt(PROVINCIAL_LEVEL);
		selectedCompanyId=provincialCompanyValue;
	}else if(municipalCompanyValue==-1){
		level=parseInt(MUNIPITAL_LEVEL);
		selectedCompanyId=-1;
		parentCompanyId=provincialCompanyValue;
	}
	//center
	else if(centerCompanyValue==0){
		level=parseInt(MUNIPITAL_LEVEL);
		selectedCompanyId=municipalCompanyValue;
	}else if(centerCompanyValue==-1){
		level=parseInt(CLAIM_CENTER_LEVEL);
		selectedCompanyId=-1;
		parentCompanyId=municipalCompanyValue;
	}else{
		level=parseInt(CLAIM_CENTER_LEVEL);
		selectedCompanyId=centerCompanyValue;
	}
	//set value to json object and convert to string from object	
	menuObj.currentSelectedCompanyId=selectedCompanyId;
	menuObj.parentCompanyId=parentCompanyId;
	menuObj.currentSelectedCompanyLevel=level;
	//set json string to hidden string
	var jsonStr=evalJSONString(menuObj);
	//clear page number
	$("#_p_currentPage_id").val("");
	$("#_p_totalPage_id").val("");	
	$("#menuLayOut").val(jsonStr);
	//submit
	submitActionByMethod('#form1','queryCompany');
}



function submitActionByMethod(formId,methodName){
	var action = $(formId).attr("action");
	$(formId).attr("action",action+"?method:"+methodName);
    $(formId).submit();
}

function ableAllSelectMenu(){
	$("#provincial").attr("disabled",false);
	$("#municipal").attr("disabled",false);
	$("#center").attr("disabled",false);
}

function hideClass(className){
	$(className).each(function(){
		$(this).css("display","none");
	});
}


function reloadDivDialog(id,width,minWidth){
	 $(id).dialog({
	        autoOpen: false,
	        modal: true,                  // 是否使用模式窗口，模式窗口打开后，页面其他元素将不能点击，直到关闭模式窗口。
	        closeOnEscape: true,           // true: 点击键盘ESC键关闭dialog
	        width: width, minWidth: minWidth, 	       
	        resizable: true,
	        draggable: false
	    });
}

function showAdd(){
	var menuLayOut=$("#menuLayOut").val();
	var menuObj=evalJSON(menuLayOut);	
	var currentSelectedCompanyId= menuObj.currentSelectedCompanyId;
	var parentCompanyId=menuObj.parentCompanyId;
	var currentSelectedCompanyLevel=menuObj.currentSelectedCompanyLevel;
	var userCompanyLevel=menuObj.userCompanyLevel;
	//get html by ajax
	var url="admin/ajaxInitializeAddCompany.action";
	var params;
	//after query company ,select current company as default,initial params
	var companyId=currentSelectedCompanyId==-1?parentCompanyId:currentSelectedCompanyId;
	//alert(companyId+', '+currentSelectedCompanyLevel);
	if(userCompanyLevel==1){
		
		if(currentSelectedCompanyLevel>2){
			params={"companyId":companyId,"companyLevel":currentSelectedCompanyLevel};
		}
	}else if(userCompanyLevel==2){
		if(currentSelectedCompanyLevel>3){
			params={"companyId":companyId,"companyLevel":currentSelectedCompanyLevel};
		}
	}
	
	var divId="#Add";
	setValueToDivByAjax(url,params,divId);
	openDivDialog('#Add');
	//after query company ,select current company as default
	
	if(userCompanyLevel==1){
		//alert('总公司');
		if(currentSelectedCompanyLevel==3){
		//	alert('currentSelectedCompanyLevel==3');
			$("#municipalradio").attr("checked",true);
			$("#provincalTr").css("display","");
		}else if(currentSelectedCompanyLevel==4){
		//	alert('currentSelectedCompanyLevel==4');
			$("#claimcenterradio").attr("checked","checked");
			$("#provincalTr").css("display","");
			$("#municipalTr").css("display","");
		}
	}else if(userCompanyLevel==2){
		//alert('省级公司');
		if(currentSelectedCompanyLevel==4){
			//alert('currentSelectedCompanyLevel==4');
			$("#claimcenterradio").attr("checked","checked");
			$("#municipalTr").css("display","");
		}
	}
	
	
}

function showParent(id){
	$(id).dialog( 'close' );
}

function showUpdate(companyId,companyLevel){	
	var url="admin/ajaxInitializeUpdateCompany.action";
	var params={"updateCompanyId":companyId,"updateCompanyLevel":companyLevel};
	var divId="#Update";
	setValueToDivByAjax(url,params,divId);
	openDivDialog('#Update');
}

function showDelete(companyId,parentCompanyId,companyLevel){	
	//load delete div
	showConfirmDialogue('确定删除吗',deleteCompany,[companyId,parentCompanyId,companyLevel]);
	
}



function deleteCompany(companyId,parentCompanyId,companyLevel){
	/*$.post("admin/ajaxCompanyDelete.action",{"companyId":companyId},function(data2){	
		if(data2==0){
			alert('该单位下面有用户或者公司，不能删除！');
		}else{
		//foward to new page
			var menuLayOut=$("#menuLayOut").val();
			var menuObj=evalJSON(menuLayOut);
		//	alert(menuObj.currentSelectedCompanyId);
			if(menuObj.currentSelectedCompanyId!=-1){
				menuObj.parentCompanyId=parentCompanyId;
				menuObj.currentSelectedCompanyId=-1;
				var jsonStr=evalJSONString(menuObj);
				$("#menuLayOut").val(jsonStr);
			}
			showAlertDialogue('删除成功',forwardToNewPage,'companyExcutePagination.action');
		}
	});	*/
	$.ajax({
        type:"POST",
        async:false,
        url:"admin/ajaxCompanyDelete.action",
        data:{"companyId":companyId},
        success:function(data2) {
        	if(data2==0){
    		
    			showAlertDialogue('该单位下面有用户或者公司，不能删除！','','');
    		}else{
    		//foward to new page
    			var menuLayOut=$("#menuLayOut").val();
    			var menuObj=evalJSON(menuLayOut);
    		//	alert(menuObj.currentSelectedCompanyId);
    			if(menuObj.currentSelectedCompanyId!=-1){
    				menuObj.parentCompanyId=parentCompanyId;
    				menuObj.currentSelectedCompanyId=-1;
    				var jsonStr=evalJSONString(menuObj);
    				$("#menuLayOut").val(jsonStr);
    			}
    			showAlertDialogue('删除成功',forwardToNewPage,'companyExcutePagination.action');
    		}}
    });	
		
}
function forwardToNewPage(url){
	$("#form1").attr("action",url);
    $("#form1").submit();
}
function setValueToDivByAjax(url,params,divId){

	//showTip();
	$.ajax({
        type:"POST",
        async:false,
        url:url,
        data:params,
        success:function(data) {
	
              	//	hideTip();
                	$(divId).empty();
    				$(divId).html(data);
              
          }
    });
}

function openDivDialog(id){
	 reloadDivDialog('#Update',500,500);
	 reloadDivDialog('#Add',500,500);
	if($(id).dialog( 'isOpen' )){	
		$(id).dialog( 'close' );
	}else{
		$(id).dialog( 'open' );
	}	
}
